package com.qf.server.impl;

import com.alibaba.fastjson.JSONObject;
import com.qf.client.UserClient;
import com.qf.dao.RedioMapper;
import com.qf.dao.RedioRespository;
import com.qf.pojo.BaseResp;
import com.qf.pojo.MvDis;
import com.qf.pojo.Redios;
import com.qf.server.RedioService;
import com.qf.utils.CookieUtils;
import com.qf.utils.JWTutils;
import com.qf.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class RedioServiceImpl implements RedioService {
    @Autowired
    RedioRespository redioRespository;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserClient userClient;
    @Autowired
    RedioMapper redioMapper;

     String key = "MV_KEY";
//    String keys = "MV_DIS";
        String key1 = "MV_KEY_SCORE";

    @Override
    public BaseResp findAllRedioByScore(){
        BaseResp baseResp = new BaseResp();
        //查询redis中是否存在该数据
        boolean b = redisUtils.hasKey(key1);
        if (!b){
            //查询所有并存放到redis中
            List<Redios> all = redioRespository.findAll();
            if(!redisUtils.hasKey(key1)){
            for (Redios redios: all
                 ) {
                //取出每个视频的分数，名称存入redis用zset方式
                    redisTemplate.opsForZSet().add(key1,redios.getId(),redios.getGood());
//                  redisUtils.expire(key1,3600);
//                redisUtils.ZSet(key1,redios.getMvName(),redios.getGood());
            }
            }
        }
        //取出前五位
        Set<String> range = redisTemplate.opsForZSet().reverseRange(key1, 0, 5);
        Iterator iterator = range.iterator();
        List list = new ArrayList();
        while (iterator.hasNext()){
            Optional<Redios> byId = redioRespository.findById(Integer.valueOf(iterator.next().toString()));
            Double score = redisTemplate.opsForZSet().score(key1, Integer.valueOf(iterator.next().toString()));
            Redios redios = byId.get();
            redios.setGood(score);
            list.add(redios);
        }
        baseResp.setCode(200);
        baseResp.setData(list);
        return baseResp;
    }

    @Override
    public BaseResp addredio(Redios redios, HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        CookieUtils cookieUtils = new CookieUtils();
        String token = cookieUtils.getToken(request);
        Object o = redisUtils.get(token);
        //JWT解析
        JWTutils jwTutils = new JWTutils();
        Map verifier = jwTutils.Verifier(o.toString());
        Integer uid = Integer.valueOf(verifier.get("id").toString());
        redios.setUid(uid);
        redios.setGood(1.0);
        Redios redios1 = redioRespository.saveAndFlush(redios);
        if (redios1!=null){
            //更新redis
            redisUtils.del(key1);
            List<Redios> all = redioRespository.findAll();
//            redisTemplate.opsForList().leftPushAll(key,all);
            for (Redios redio: all
            ) {
                redisTemplate.opsForZSet().add(key1,redio.getId(),redio.getGood());
            }
            baseResp.setCode(200);
            baseResp.setMessage("上传成功");
        }
        return baseResp;
    }


    @Override
    public BaseResp findAllRedio(Integer page,Integer size) {
        BaseResp baseResp = new BaseResp();
        //查询redis中是否存在该数据
         boolean b = redisUtils.hasKey(key);
         if (!b){
             //查询所有并存放到redis中
//             PageRequest pageRequest = new PageRequest(page,size);
//             Page<Redios> all1 = redioRespository.findAll(pageRequest);
//             List<Redios> content = all1.getContent();
//             long totalElements = all1.getTotalElements();
             List<Redios> all = redioRespository.findAll();
//             if(!redisUtils.hasKey(key1)){
//             for (Redios redios: all
//                  ) {
//                 redisTemplate.opsForZSet().add(key1,redios.getId(),redios.getGood());
//             }
//         }
             redisTemplate.opsForList().leftPushAll(key,all);
         }
         //从redis中进行获取并进行分页
         int startRow =(page-1)*size;
        int endRow =startRow+size;
         List range = redisTemplate.opsForList().range(key, startRow, endRow - 1);
         //从redis中获取到总的条数
         Long size1 = redisTemplate.opsForList().size(key);
//        Set<String> range = redisTemplate.opsForZSet().reverseRange(key1, 0, - 1);
//        Iterator iterator = range.iterator();
//        List list = new ArrayList();
//        while (iterator.hasNext()){
//            Optional<Redios> byId = redioRespository.findById(Integer.valueOf(iterator.next().toString()));
//            Double score = redisTemplate.opsForZSet().score(key1, Integer.valueOf(iterator.next().toString()));
//            Redios redios = byId.get();
//            redios.setGood(score);
//            list.add(redios);
//        }
//        Long size1 = redisTemplate.opsForZSet().size(key1);
        baseResp.setCode(200);
         baseResp.setData(range);
         baseResp.setTotal(size1);
         return baseResp;

    }

    @Override
    public BaseResp addgood(Integer id) {
        BaseResp baseResp = new BaseResp();
            //更新redis的zset得分点赞数+1
             redisTemplate.opsForZSet().incrementScore(key1, id, 1);
//            Set<String> range = redisTemplate.opsForZSet().reverseRange(key1, 0, -1);
//        Iterator iterator = range.iterator();
//        List list = new ArrayList();
//        while (iterator.hasNext()){
//            Optional<Redios> byId = redioRespository.findById(Integer.valueOf(iterator.next().toString()));
//            Double score = redisTemplate.opsForZSet().score(key1, Integer.valueOf(iterator.next().toString()));
//            Redios redios = byId.get();
//            redios.setGood(score);
//            list.add(redios);
//        }
//            Redios redios = byId.get();
//           redios.setGood(redios.getGood()+1);
//           //更新后的数据存入数据库
//            redioRespository.saveAndFlush(redios);
            //更新redis
//            redisUtils.del(key);
//            List<Redios> all = redioRespository.findAll();
//            redisTemplate.opsForList().leftPushAll(key,all);
            baseResp.setCode(200);
            baseResp.setMessage("点赞成功");
//            baseResp.setData(list);
        return baseResp;
    }

    @Override
    public BaseResp findUserByToId(Map map) {
         //通过id获取uid
        Optional<Redios> byId = redioRespository.findById(Integer.valueOf(map.get("id").toString()));
        Map map1 = new HashMap();
        if (byId.isPresent()){
            Redios redios = byId.get();
            Integer uid = redios.getUid();
            map1.put("id",uid);
        }
        return userClient.findUserByToId(map1);
    }

    @Override
    public BaseResp findMvShareById(Map map) {
        BaseResp baseResp = new BaseResp();
        Optional<Redios> byId = redioRespository.findById(Integer.valueOf(map.get("id").toString()));
        if (byId.isPresent()){
            baseResp.setCode(200);
            baseResp.setMessage("查询成功");
            baseResp.setData(byId.get());
        }
        return baseResp;
    }

    @Override
    public BaseResp findcomments(Integer id) {
        List<MvDis> mvDis = redioMapper.selectAllDis(id);
        BaseResp baseResp = new BaseResp();
        baseResp.setCode(200);
             baseResp.setMessage("查询成功");
             baseResp.setData(mvDis);
            return baseResp;

//        boolean b = redisUtils.hasKey(keys + "_" + id.toString());
//        BaseResp baseResp = new BaseResp();
//        if (!b){
//        baseResp.setCode(202);
//
//        baseResp.setMessage("该视频还没有评论，快来抢占沙发位！");
//        return baseResp;
//        }else {
//            List<Object> objects = redisUtils.lGet(keys + "_" + id.toString(), 0, 1);
//             baseResp.setCode(200);
//             baseResp.setMessage("查询成功");
//             baseResp.setData(objects);
//            return baseResp;
//        }

    }

    @Override
    public BaseResp addcomments(Map map) {
        BaseResp baseResp = new BaseResp();

        MvDis mvDis = new MvDis();
        mvDis.setMid(Integer.valueOf(map.get("id").toString()));
        mvDis.setMvdis_desc(map.get("comments").toString());
        mvDis.setUid(Integer.valueOf(map.get("uid").toString()));
        redioMapper.addMvDis(mvDis);
        baseResp.setCode(200);
        baseResp.setMessage("评论成功");
        return baseResp;
    }
}
